/**
 * Author(s): xuming.Wong <xuming.Wong@gmail.com>
 */
#include "TransactionDownloadWidget.h"

#include <QtCore/QTime>
#include <QtGui/QEvent.h>
#include <QtGui/QMessageBox>

#include <QtGui/QGridLayout>
#include <QtGui/QPushButton>

#include <QtGui/QHBoxLayout>
#include <QtGui/QTextBlock>
#include <QtGui/QLabel>
#include "Utilities.h"
#include "StockDatabase.h"
#include "TransactionDownloader.h"
#include "TransactionDatabase.h"


namespace QSThink
{

	TransactionDownloadWidget::TransactionDownloadWidget(QWidget *parent,Qt::WindowFlags flag)
		:QWidget(parent,flag),_ui(new Ui::TransactionDownloadUI),_completer(0),_contextMenu(0),
		_dataViewDialog(0),_dataDiagramDialog(0)
	{
		
		_ui->setupUi(this);
		_ui->dateEditStart->setHidden(true);
		_ui->dateEditEnd->setHidden(true);
		_ui->progressBar->setHidden(true);
		_ui->buttonDownload->setHidden(true);
		//set date when date loaded

		connect(_ui->lineEdit, SIGNAL(textChanged(const QString &)), this, SLOT(symbolChanged(const QString &)));
		connect(_ui->lineEdit, SIGNAL(textEdited(const QString &)), this, SLOT(symbolEdited(const QString &)));
		connect(_ui->buttonAdd, SIGNAL(clicked()), this, SLOT(addSymbol()));
		connect(_ui->buttonDownload, SIGNAL(clicked()), this, SLOT(downloadButtonClicked()));


		connect(_ui->listItem,SIGNAL(itemDoubleClicked(QListWidgetItem*)),this, SLOT(OnItemDoubleClicked(QListWidgetItem*)));
		connect(_ui->listItemDownloaded,SIGNAL(itemDoubleClicked(QListWidgetItem*)),this, SLOT(OnDownItemDoubleClicked(QListWidgetItem*)));

		
		connect(_ui->dateEditStart,SIGNAL(dateChanged(const QDate &)),this, SLOT(dateStartChanged(const QDate &)));
		connect(_ui->dateEditEnd,SIGNAL(dateChanged(const QDate &)),this, SLOT(dateEndChanged(const QDate &)));


		setMinimumSize(600,400);

		setInputCompleter();


		this->setContextMenuPolicy(Qt::DefaultContextMenu);

		loadDownloadTask();


		QDate date=QDate::currentDate().addDays(-1);
		_startDate=date;
		_endDate=date;
		_ui->dateEditStart->setDate(date);
		_ui->dateEditEnd->setDate(date);

		

	}

	
	TransactionDownloadWidget::~TransactionDownloadWidget()
	{
		destroy();
	}

	void TransactionDownloadWidget::setInputCompleter()
	{
		if(_completer){
			return;
		}
		_completer = new QCompleter(this);
		_completer->setMaxVisibleItems(10);
		_completer->setModel(Utilities::loadSymbolModel());

		QTreeView *treeView = new QTreeView;
		_completer->setPopup(treeView);
		treeView->setRootIsDecorated(false);
		treeView->header()->hide();
		treeView->header()->setStretchLastSection(false);
		treeView->header()->setResizeMode(0, QHeaderView::ResizeToContents);
		treeView->header()->setResizeMode(1, QHeaderView::ResizeToContents);
		treeView->header()->setResizeMode(2, QHeaderView::ResizeToContents);

		_completer->setCompletionColumn(1);

		_ui->lineEdit->setCompleter(_completer);

		connect(_completer, SIGNAL(activated(const QModelIndex &)), this, SLOT(symbolSelected(const QModelIndex &)));


	}

	void TransactionDownloadWidget::symbolSelected(const QModelIndex &index)
	{

		QAbstractItemModel *model=_completer->completionModel();
		QModelIndex i=model->index(index.row(),0);
		QVariant var=model->data(i);

		_symbolEdit=var.toString();

		_ui->lineEdit->setText(_symbolEdit);


	}

	void TransactionDownloadWidget::symbolChanged( const QString & symbol )
	{
		_ui->lineEdit->setText(_symbolEdit);

	}

	void TransactionDownloadWidget::symbolEdited( const QString &symbol )
	{
		_symbolEdit=_ui->lineEdit->text();

	}

	void TransactionDownloadWidget::addSymbol()
	{
		//
		QString symbol=_ui->lineEdit->text();

		SymbolToItemMap::iterator it=_symbolToItems.find(symbol);
		if(it!=_symbolToItems.end()){
			//find just return
			return;
		}


		if(!StockDatabase::getSingleton().hasSymbol(symbol)){
			return;
		}

		QString name=StockDatabase::getSingleton().getStockName(symbol);

		QString fullname=symbol;
		fullname+=" ";
		fullname+=name;

		QListWidgetItem* item=new QListWidgetItem(fullname);

		_ui->listItem->addItem(item);

		_itemToSymbols.insert(ItemToSymbolMap::value_type(item,symbol));
		_symbolToItems.insert(SymbolToItemMap::value_type(symbol,item));
		
		
		persit();


		QDate dateStart=_ui->dateEditStart->date();
		QDate dateEnd=_ui->dateEditEnd->date();
		TransactionDownloader::getSingleton().addTask(symbol,dateStart,dateEnd);

	}

	void TransactionDownloadWidget::persit()
	{
		
	}

	void TransactionDownloadWidget::openDataTable()
	{
		//_ui->listItemDownloaded->
	}

	void TransactionDownloadWidget::contextMenuEvent( QContextMenuEvent * evt )
	{

		if(!_contextMenu){
			_contextMenu=new QMenu(this);
			QAction *startDownloadAction=_contextMenu->addAction("open data table");
			connect(startDownloadAction, SIGNAL(triggered()), this, SLOT(openDataTable()));

		}

		QPoint globalPos=this->mapToGlobal(evt->pos());

		QListWidgetItem* item=_ui->listItemDownloaded->itemAt(_ui->listItemDownloaded->mapFromGlobal(globalPos));
		if(item){
			_contextMenu->popup(globalPos);
		}

	}

	

	void TransactionDownloadWidget::OnDownItemDoubleClicked( QListWidgetItem* item )
	{
		QString dateStr=item->text();

		QDate date=Utilities::getDateByStr(dateStr);
		
		Transaction1Day* trans=TransactionDatabase::getSingleton().getDayTransaction(_symbolSelect,date);

		//showDayTransDialog(trans);
		
		showDayTransGraphicsDialog(_symbolSelect,date);

	}

	void TransactionDownloadWidget::OnItemDoubleClicked( QListWidgetItem* item )
	{
		
		_ui->dateEditStart->setHidden(false);
		_ui->dateEditEnd->setHidden(false);
		_ui->progressBar->setHidden(false);
		_ui->buttonDownload->setHidden(false);
		_ui->listItemDownloaded->clear();
		
		ItemToSymbolMap::iterator it=_itemToSymbols.find(item);
		if(it!=_itemToSymbols.end()){
			QString symbol=it->second;
			_symbolSelect=symbol;
			QDate date=StockDatabase::getSingleton().getStockPublicDate(symbol);
			_ui->dateEditStart->setDate(date);
			
			loadDownloadedItems(symbol);
			

		}
		
	}

	void TransactionDownloadWidget::loadDownloadedItems(QString symbol)
	{
		TransactionDownloadTask* task=TransactionDownloader::getSingleton().getTask(symbol);
		if(task->inited()){
			_ui->dateEditStart->setDate(task->startDate());
			_ui->dateEditEnd->setDate(task->endDate());


			int daysLeft=task->dayLeftCount();
			int daysDown=task->dayDownCount();
			int daysTotal=task->daysTotal();

			for(int i=0;i<daysDown;++i){
				Transaction1Day* trans=task->getDownDayTrans(i);
				QDate dt=trans->date();
				int dayOfWeed=dt.dayOfWeek();
				QString itemName=Utilities::getDateStr(dt);
				//itemName+=" ";
				//itemName+=QString::number(dayOfWeed);

				QListWidgetItem* item=new QListWidgetItem(itemName);
				_ui->listItemDownloaded->addItem(item);
			}

			_ui->progressBar->setMinimum(0);

			_ui->progressBar->setMaximum(daysTotal);

			_ui->progressBar->setValue(daysDown);
			_ui->listItemDownloaded->sortItems();
		}
	}

	void TransactionDownloadWidget::downloadButtonClicked()
	{
		QDate dateStart=_ui->dateEditStart->date();
		QDate dateEnd=_ui->dateEditEnd->date();


		//
		QListWidgetItem* item=_ui->listItem->currentItem();

		ItemToSymbolMap::iterator it=_itemToSymbols.find(item);
		if(it==_itemToSymbols.end()){
			//Not find
			return;

		}

		QString symbol=it->second;

		TransactionDownloadTask* task= TransactionDownloader::getSingleton().getTask(symbol);
		task->setStartEndDate(dateStart,dateEnd);
		task->start();


		_ui->progressBar->setMinimum(0);
		_ui->progressBar->setMaximum(task->daysTotal());
		_ui->progressBar->setValue(task->dayDownCount());

	}

	void TransactionDownloadWidget::loadDownloadTask()
	{
		_ui->listItem->setSortingEnabled(true);
		int cnt=TransactionDownloader::getSingleton().getTaskCount();
		for (int i=0;i<cnt;++i){
			TransactionDownloadTask* task=TransactionDownloader::getSingleton().getTask(i);
			QString symbol=task->symbol();
			QString name=StockDatabase::getSingleton().getStockName(symbol);

			QString fullname=symbol;
			fullname+=" ";
			fullname+=name;

			QListWidgetItem* item=new QListWidgetItem(fullname);
			_ui->listItem->addItem(item);
			

			_itemToSymbols.insert(ItemToSymbolMap::value_type(item,symbol));
			_symbolToItems.insert(SymbolToItemMap::value_type(symbol,item));

		}

		_ui->listItemDownloaded->sortItems();

	}

	void TransactionDownloadWidget::dateStartChanged( const QDate & date )
	{

		if(_startDate==date){
			return;
		}
		QListWidgetItem* item=_ui->listItem->currentItem();
		ItemToSymbolMap::iterator it=_itemToSymbols.find(item);
		if(it==_itemToSymbols.end()){
			//Not find
			return;

		}

		//find
		QString symbol=it->second;

		

		//TransactionDownloadTask* task=TransactionDownloader::getSingleton().getTask(symbol);
		//task->setStartDate(date);

	}

	void TransactionDownloadWidget::dateEndChanged( const QDate & date )
	{
		if(_endDate==date){
			return;
		}

		QListWidgetItem* item=_ui->listItem->currentItem();
		ItemToSymbolMap::iterator it=_itemToSymbols.find(item);
		if(it==_itemToSymbols.end()){
			//Not find
			return;

		}

		//find
		QString symbol=it->second;


		//TransactionDownloadTask* task=TransactionDownloader::getSingleton().getTask(symbol);
		//task->setEndDate(date);


	}

	void TransactionDownloadWidget::OnDayTransactionDownloaded(Transaction1Day* trans )
	{
		addDayTransactionItem(trans);

		QString symbol=trans->symbol();
		TransactionDownloadTask* task= TransactionDownloader::getSingleton().getTask(symbol);

		_ui->progressBar->setValue(task->dayDownCount());
		_ui->progressBar->setMaximum(task->daysTotal());

	}

	void TransactionDownloadWidget::addDayTransactionItem( Transaction1Day* trans )
	{
		QListWidgetItem* itemLeft=_ui->listItem->currentItem();

		QString symbol=trans->symbol();

		SymbolToItemMap::iterator it=_symbolToItems.find(symbol);
		if(it!=_symbolToItems.end()){
			//find
			if(it->second!=itemLeft){
				return;
			}
		}else{
			return;//not find just return 
		}

		QDate date=trans->date();
		int dayOfWeed=date.dayOfWeek();
		QString itemName=Utilities::getDateStr(date);
		//itemName+=" ";
		//itemName+=QString::number(dayOfWeed);

		QListWidgetItem* item=new QListWidgetItem(itemName);
		_ui->listItemDownloaded->addItem(item);
		

		

	}

	void TransactionDownloadWidget::OnTaskFinished( TransactionDownloadTask* task )
	{

	}

	void TransactionDownloadWidget::showDayTransDialog(Transaction1Day* trans)
	{
		if(!_dataViewDialog){
			_dataViewDialog=new TransactionViewDialog(this);

		}

		_dataViewDialog->load(trans);
		_dataViewDialog->show();
	}

	void TransactionDownloadWidget::showDayTransGraphicsDialog( QString symbol, QDate date )
	{
		if(!_dataDiagramDialog){
			_dataDiagramDialog=new DiagramDialog(this);

		}

		_dataDiagramDialog->load(symbol,date);
		_dataDiagramDialog->show();
	}

}
